package com.alibaba.citrus.cr.platform.enhance.functions.utils;

import java.text.ParseException;
import java.text.SimpleDateFormat;
import java.util.ArrayList;
import java.util.Date;
import java.util.HashMap;
import java.util.List;
import java.util.Map;
import java.util.Objects;
import java.util.stream.Collectors;

import com.alibaba.citrus.cr.common.exception.FunctionException;
import com.alibaba.citrus.cr.common.util.DateUtils;
import com.alibaba.fastjson.JSONObject;

import com.epoch.app.crplatformenhance.enums.DimensionTypeEnum;
import com.epoch.app.crplatformenhance.enums.StrategyTypeEnum;
import com.epoch.app.crplatformenhance.model.dto.*;
import com.epoch.app.crplatformenhance.model.enums.RuleTypeEnum;
import com.epoch.app.crplatformenhance.sdo.DimensionSDO;
import com.epoch.app.crplatformenhance.sdo.StrategySDO;
import com.epoch.app.crplatformenhance.strategy.model.Strategy;
import org.apache.commons.collections4.CollectionUtils;
import org.springframework.util.StringUtils;

public class ConverterUtils {

    public static StrategySDO createStrategyConverter(StrategyWriteCreateRequest request) {
        StrategySDO strategySDO = new StrategySDO();
        strategySDO.setId(request.getId());
        strategySDO.setName(request.getName());
        strategySDO.setGmtCreate(new Date());
        strategySDO.setCreator(request.getCreator());
        strategySDO.setPriority(request.getPriority());
        strategySDO.setDimensionType(request.getDimensionType());
        strategySDO.setShare(request.getShare());
        strategySDO.setDailyBeginTime(request.getDailyBeginTime());
        strategySDO.setDailyEndTime(request.getDailyEndTime());
        if (CollectionUtils.isNotEmpty(request.getStrategyValid())) {
            SimpleDateFormat sdf = new SimpleDateFormat(DateUtils.DATETIME_FORMAT);
            try {
                strategySDO.setValidBeginTime(sdf.parse(request.getStrategyValid().get(0)));
                Date lastTime = DateUtils.getLastTime(request.getStrategyValid().get(1));
                strategySDO.setValidEndTime(lastTime);
            } catch (ParseException e) {
                e.printStackTrace();
            }
        }
        strategySDO.setType(request.getType());
        strategySDO.setOrganizationCode(request.getOrganizationCode());
        strategySDO.setOrganizationName(request.getOrganizationName());
        strategySDO.setStatus(request.getStatus());
        List<DimensionSDO> dimensionSDOS = new ArrayList<>();
        //维度
        if (!CollectionUtils.isEmpty(request.getValid())) {
            DimensionSDO dimensionSDO = new DimensionSDO();
            dimensionSDO.setCode(request.getDimensionCode());
            //判断传过来的纬度值中是否包含"-"
            if (!StringUtils.isEmpty(request.getDimensionValue())) {
                if (request.getDimensionValue().contains(":")) {
                    String[] split = request.getDimensionValue().split(":");
                    dimensionSDO.setValue(split[1]);
                    dimensionSDO.setValueName(split[0]);
                } else {
                    dimensionSDO.setValue(request.getDimensionValue());
                }
            }
            if (!StringUtils.isEmpty(request.getOrgValue())) {
                if (request.getOrgValue().contains(":")) {
                    String[] split = request.getOrgValue().split(":");
                    dimensionSDO.setValue(split[1]);
                    dimensionSDO.setValueName(split[0]);
                } else {
                    dimensionSDO.setValue(request.getOrgValue());
                }
            }
            dimensionSDO.setRuleName(request.getRule());
            dimensionSDO.setRuleValue(request.getRuleValue());
            dimensionSDO.setStatus(request.getDimensionStatus());
            dimensionSDO.setCodeName(DimensionTypeEnum.of(request.getDimensionCode()).getDesc());
            if (!CollectionUtils.isEmpty(request.getValid())) {
                SimpleDateFormat sdf = new SimpleDateFormat(DateUtils.DATETIME_FORMAT);
                try {
                    Date begin = sdf.parse(request.getValid().get(0));
                    Date lastTime = DateUtils.getLastTime(request.getValid().get(1));
                    dimensionSDO.setValidBeginTime(begin);
                    dimensionSDO.setValidEndTime(lastTime);
                } catch (ParseException e) {
                    e.printStackTrace();
                }
            }
            dimensionSDO.setExecuteAction(Objects.nonNull((request.getExecuteAction())) && request.getExecuteAction());
            dimensionSDO.setDetails(JSONObject.toJSONString(request.getRatioMap()));
            dimensionSDO.setStrategyId(request.getStrategyId());
            dimensionSDO.setDetails(request.getDetails());
            dimensionSDOS.add(dimensionSDO);
            strategySDO.setDimensionSDOList(dimensionSDOS);
        }

        if (CollectionUtils.isNotEmpty(request.getScItemList())) {
            List<DimensionSDO> dimensionSDOList = request.getScItemList().stream().map(scItem -> {
                DimensionSDO dimensionSDO = new DimensionSDO();
                dimensionSDO.setStatus(request.getStatus());
                dimensionSDO.setValue(scItem.split(":")[1]);
                dimensionSDO.setValueName(scItem.split(":")[0]);
                dimensionSDO.setCode(DimensionTypeEnum.GOODS.getCode());
                dimensionSDO.setCodeName(DimensionTypeEnum.of(DimensionTypeEnum.GOODS.getCode()).getDesc());
                return dimensionSDO;
            }).collect(Collectors.toList());
            strategySDO.setDimensionSDOList(dimensionSDOList);
        }
        if (CollectionUtils.isNotEmpty(request.getWarehouseList())) {
            List<DimensionSDO> collect = request.getWarehouseList().stream().map(warehouse -> {
                DimensionSDO dimensionSDO = new DimensionSDO();
                dimensionSDO.setStatus(request.getStatus());
                //标识为逻辑仓
                dimensionSDO.setCode(DimensionTypeEnum.STORE_ROOM.getCode());
                dimensionSDO.setValue(warehouse.split(":")[1]);
                dimensionSDO.setValueName(warehouse.split(":")[0]);
                return dimensionSDO;
            }).collect(Collectors.toList());
            strategySDO.setDimensionSDOList(collect);
        }
        if (CollectionUtils.isNotEmpty(request.getCustomerList())) {
            List<DimensionSDO> collect = request.getCustomerList().stream().map(customer -> {
                DimensionSDO dimensionSDO = new DimensionSDO();
                dimensionSDO.setStatus(request.getStatus());
                //标识为逻辑仓
                dimensionSDO.setCode(request.getDimensionCode());
                dimensionSDO.setValue(customer.split(":")[1]);
                dimensionSDO.setValueName(customer.split(":")[0]);
                return dimensionSDO;
            }).collect(Collectors.toList());
            strategySDO.setDimensionSDOList(collect);
        }
        if (CollectionUtils.isNotEmpty(request.getDepartmentList())) {
            List<DimensionSDO> collect = request.getDepartmentList().stream().map(department -> {
                DimensionSDO dimensionSDO = new DimensionSDO();
                dimensionSDO.setStatus(request.getStatus());
                //标识为逻辑仓
                dimensionSDO.setCode(request.getDimensionCode());
                dimensionSDO.setValue(department.split(":")[1]);
                dimensionSDO.setValueName(department.split(":")[0]);
                return dimensionSDO;
            }).collect(Collectors.toList());
            strategySDO.setDimensionSDOList(collect);
        }
        if (CollectionUtils.isNotEmpty(request.getChannelList())) {
            List<DimensionSDO> collect = request.getChannelList().stream().map(channel -> {
                DimensionSDO dimensionSDO = new DimensionSDO();
                dimensionSDO.setStatus(request.getStatus());
                //标识为逻辑仓
                dimensionSDO.setCode(request.getDimensionCode());
                dimensionSDO.setValue(channel.split(":")[1]);
                dimensionSDO.setValueName(channel.split(":")[0]);
                return dimensionSDO;
            }).collect(Collectors.toList());
            strategySDO.setDimensionSDOList(collect);
        }
        if (CollectionUtils.isNotEmpty(request.getSalesmanList())) {
            List<DimensionSDO> collect = request.getSalesmanList().stream().map(salesman -> {
                DimensionSDO dimensionSDO = new DimensionSDO();
                dimensionSDO.setStatus(request.getStatus());
                //标识为逻辑仓
                dimensionSDO.setCode(request.getDimensionCode());
                dimensionSDO.setValue(salesman.split(":")[1]);
                dimensionSDO.setValueName(salesman.split(":")[0]);
                return dimensionSDO;
            }).collect(Collectors.toList());
            strategySDO.setDimensionSDOList(collect);
        }
        return strategySDO;
    }

    /**
     * 库存路由策略参数转换
     *
     * @param request
     * @return
     */
    public static StrategySDO createInventoryRoutingParams(StrategyInventoryRoutWriteCreateRequest request) {
        StrategySDO strategySDO = new StrategySDO();
        strategySDO.setId(request.getId());
        List<DimensionSDO> dimensionSDOList=new ArrayList<>();
        //设置仓库拆分子单
        if (CollectionUtils.isNotEmpty(request.getWarehouseList())) {
            List<Map<String,String>> warehouseList = request.getWarehouseList();
            List<DimensionSDO> collect = warehouseList.stream().filter(it -> it.containsKey("valueName")).map(warehouse -> {
                DimensionSDO dimensionSDO = new DimensionSDO();
                dimensionSDO.setStatus(request.getStatus());
                //标识为逻辑仓
                dimensionSDO.setCode(DimensionTypeEnum.STORE_ROOM.getCode());
                dimensionSDO.setValue(warehouse.get("valueName").split(":")[1]);
                dimensionSDO.setValueName(warehouse.get("valueName").split(":")[0]);
                return dimensionSDO;
            }).collect(Collectors.toList());
            if (checkRepeat(collect)) {
                throw new FunctionException("OTS-04-001-00-15-046");
            }
            dimensionSDOList.addAll(collect);
        }
        //分公司
        if (CollectionUtils.isNotEmpty(request.getDepartmentList())) {
            List<Map<String, String>> departmentList = request.getDepartmentList();
            List<DimensionSDO> collect = departmentList.stream().filter(it -> it.containsKey("valueName")).map(department -> {
                DimensionSDO dimensionSDO = new DimensionSDO();
                dimensionSDO.setStatus(request.getStatus());
                //标识为分公司
                dimensionSDO.setCode(DimensionTypeEnum.DEPARTMENT.getCode());
                dimensionSDO.setValue(department.get("valueName").split(":")[1]);
                dimensionSDO.setValueName(department.get("valueName").split(":")[0]);
                return dimensionSDO;
            }).collect(Collectors.toList());
            if (checkRepeat(collect)) {
                throw new FunctionException("OTS-04-001-00-15-043");
            }
            dimensionSDOList.addAll(collect);
        }
        //货品
        if (CollectionUtils.isNotEmpty(request.getScItemList())) {
            List<Map<String,String>> scItemList = request.getScItemList();
            List<DimensionSDO> collect = scItemList.stream().filter(it -> it.containsKey("valueName")).map(scItem -> {
                DimensionSDO dimensionSDO = new DimensionSDO();
                dimensionSDO.setStatus(request.getStatus());
                dimensionSDO.setValue(scItem.get("valueName").split(":")[1]);
                dimensionSDO.setValueName(scItem.get("valueName").split(":")[0]);
                dimensionSDO.setCode(DimensionTypeEnum.GOODS.getCode());
                dimensionSDO.setCodeName(DimensionTypeEnum.of(DimensionTypeEnum.GOODS.getCode()).getDesc());
                return dimensionSDO;
            }).collect(Collectors.toList());
            if (checkRepeat(collect)) {
                throw new FunctionException("OTS-04-001-00-15-044");
            }
            dimensionSDOList.addAll(collect);
        }
        //货品組
        if (CollectionUtils.isNotEmpty(request.getGroupProductList())) {
            List<Map<String,String>> groupProductList = request.getGroupProductList();
            List<DimensionSDO> collect = groupProductList.stream().filter(it -> it.containsKey("valueName")).map(scItem -> {
                DimensionSDO dimensionSDO = new DimensionSDO();
                dimensionSDO.setStatus(request.getStatus());
                dimensionSDO.setValue(scItem.get("valueName").split(":")[1]);
                dimensionSDO.setValueName(scItem.get("valueName").split(":")[0]);
                dimensionSDO.setCode(DimensionTypeEnum.GROUPPRODUCT.getCode());
                dimensionSDO.setCodeName(DimensionTypeEnum.of(DimensionTypeEnum.GROUPPRODUCT.getCode()).getDesc());
                return dimensionSDO;
            }).collect(Collectors.toList());
            if (checkRepeat(collect)) {
                throw new FunctionException("OTS-04-001-00-15-045");
            }
            dimensionSDOList.addAll(collect);
        }
        strategySDO.setDimensionSDOList(dimensionSDOList);
        return strategySDO;
    }
    private static boolean checkRepeat(List<DimensionSDO> dimensionSDOList) {
        Map<Object, Long> collect2 = dimensionSDOList.stream().collect(
            Collectors.groupingBy(DimensionSDO::getValue, Collectors.counting()));
        //筛出有重复的value
        List<Object> collect3 = collect2.keySet().stream().
            filter(key -> collect2.get(key) > 1).collect(Collectors.toList());
        if (CollectionUtils.isNotEmpty(collect3) && collect3.size() >=1) {
            return true;
        }
        return false;
    }

    public static StrategySDO updateStrategyConverter(StrategyWriteUpdateRequest request) {
        StrategySDO strategySDO = new StrategySDO();
        strategySDO.setId(request.getId());
        strategySDO.setGmtModified(new Date());
        strategySDO.setName(request.getName());
        strategySDO.setStatus(request.getStatus());
        strategySDO.setUpdater(request.getUpdater());
        strategySDO.setValidBeginTime(request.getValidBeginTime());
        strategySDO.setValidEndTime(request.getValidEndTime());
        strategySDO.setType(request.getType());
        strategySDO.setOrganizationCode(request.getOrganizationCode());
        strategySDO.setOrganizationName(request.getOrganizationName());
        return strategySDO;
    }

    public static StrategyLoadListRequest pageQueryConverter(StrategyPageQueryRequest request) {
        StrategyLoadListRequest strategyLoadListRequest = new StrategyLoadListRequest();
        strategyLoadListRequest.setName(request.getStrategyName());
        strategyLoadListRequest.setOrganizationCode(request.getOrganizationCode());
        strategyLoadListRequest.setOrganizationCodes(request.getOrganizationCodes());
        strategyLoadListRequest.setStatus(request.getStatus());
        strategyLoadListRequest.setType(request.getType());
        strategyLoadListRequest.setAsc(false);
        strategyLoadListRequest.setStart(request.getStart());
        strategyLoadListRequest.setLimit(request.getLimit());
        strategyLoadListRequest.setDir("gmt_create");
        return strategyLoadListRequest;
    }

    public static StrategyPageQueryResponse pageQueryResponseConverter(Strategy strategy) {
        StrategyPageQueryResponse strategyPageQueryResponse = new StrategyPageQueryResponse();
        strategyPageQueryResponse.setStrategyName(strategy.getName());
        strategyPageQueryResponse.setOrganizationCode(strategy.getOrganizationCode());
        strategyPageQueryResponse.setOrganizationName(strategy.getOrganizationName());
        strategyPageQueryResponse.setValidBeginTime(strategy.getValidBeginTime());
        strategyPageQueryResponse.setValidEndTime(strategy.getValidEndTime());
        strategyPageQueryResponse.setPriority(strategy.getPriority());
        if (null != strategy.getId()) {
            strategyPageQueryResponse.setId(String.valueOf(strategy.getId()));
        }

        if (null != strategy.getId()) {
            strategyPageQueryResponse.setStrategyId(String.valueOf(strategy.getId()));
        }
        if (strategy.getType().equals(StrategyTypeEnum.DAILY_INVENTORY.getCode())) {
            Date date = new Date();
            if (strategy.getValidBeginTime().after(date)) {
                strategyPageQueryResponse.setStatus("未生效");
                Map statusLabel = new HashMap<>();
                statusLabel.put("text","未生效");
                statusLabel.put("type","warning");
                strategyPageQueryResponse.setStatusLabel(statusLabel);
            }
            if (strategy.getValidBeginTime().before(date) && strategy.getValidEndTime().after(date)) {
                strategyPageQueryResponse.setStatus("生效中");
                Map statusLabel = new HashMap<>();
                statusLabel.put("text","生效中");
                statusLabel.put("type","success");
                strategyPageQueryResponse.setStatusLabel(statusLabel);
            }
            if ((strategy.getValidEndTime().before(date))) {
                strategyPageQueryResponse.setStatus("已失效");
                Map statusLabel = new HashMap<>();
                statusLabel.put("text","已失效");
                statusLabel.put("type","cancel");
                strategyPageQueryResponse.setStatusLabel(statusLabel);
            }
        }
        if (DimensionTypeEnum.CHANNEL.getCode().equals(strategy.getDimensionType())) {
            strategyPageQueryResponse.setDimensionTypeDesc(DimensionTypeEnum.CHANNEL.getDesc());
        }
        if (DimensionTypeEnum.DEPARTMENT.getCode().equals(strategy.getDimensionType())) {
            strategyPageQueryResponse.setDimensionTypeDesc(DimensionTypeEnum.DEPARTMENT.getDesc());
        }
        if (DimensionTypeEnum.SALESMAN.getCode().equals(strategy.getDimensionType())) {
            strategyPageQueryResponse.setDimensionTypeDesc(DimensionTypeEnum.SALESMAN.getDesc());
        }
        //库存路由策略添加返回主单状态
        if (StrategyTypeEnum.INVENTORY_ROUTING.getCode().equals(strategy.getType())) {
            strategyPageQueryResponse.setStatus(strategy.getStatus());
        }
        return strategyPageQueryResponse;
    }

    public static DimensionSDO deleteDimensionConverter(DimensionWriteDeleteRequest request) {
        DimensionSDO dimensionSDO = new DimensionSDO();
        if (!StringUtils.isEmpty(request.getId())) {
            dimensionSDO.setId(Long.parseLong(request.getId()));
        }
        return dimensionSDO;
    }

    public static StrategySDO deleteStrategyConverter(StrategyQueryByIdResponse result) {
        return result.getStrategySDO();
    }

    public static DimensionSDO updateDimensionConverter(DimensionWriteUpdateRequest request, DimensionSDO dimensionSDO) {
        if (request.getId() != null) {
            dimensionSDO.setId(Long.parseLong(request.getId()));
        }
        dimensionSDO.setCode(request.getCode());
        dimensionSDO.setValue(request.getValue());
        dimensionSDO.setRuleName(request.getRuleName());
        dimensionSDO.setRuleValue(request.getRuleValue());
        if (request.getStatus() != null) {
            dimensionSDO.setStatus(request.getStatus().toString());
        }
        dimensionSDO.setValidBeginTime(request.getValidBeginTime());
        dimensionSDO.setValidEndTime(request.getValidEndTime());
        dimensionSDO.setExecuteAction(Objects.nonNull((request.getExecuteAction())) && request.getExecuteAction());
        dimensionSDO.setStrategyId(request.getStrategyId());
        dimensionSDO.setDetails(request.getDetails());
        dimensionSDO.setCreator(request.getCreator());
        dimensionSDO.setUpdater(request.getUpdater());
        return dimensionSDO;
    }

    public static StrategySDO strategyWriteUpdateRequestConverter(StrategyWriteCreateRequest request) throws ParseException {
        StrategySDO strategySDO = new StrategySDO();
        strategySDO.setId(request.getStrategyId());
        strategySDO.setName(request.getName());
        strategySDO.setUpdater(request.getUpdater());
        strategySDO.setStatus(request.getStatus());
        if (!CollectionUtils.isEmpty(request.getStrategyValid())) {
            SimpleDateFormat sdf = new SimpleDateFormat(DateUtils.DATE_FORMAT);
            strategySDO.setValidBeginTime(sdf.parse(request.getStrategyValid().get(0)));
            Date lastTime = DateUtils.getLastTime(request.getStrategyValid().get(1));
            strategySDO.setValidEndTime(lastTime);
        }
        strategySDO.setType(request.getType());
        strategySDO.setOrganizationCode(request.getOrganizationCode());
        strategySDO.setOrganizationName(request.getOrganizationName());
        return strategySDO;
    }

    public static DimensionWriteUpdateRequest dimensionWriteUpdateRequestConverter(StrategyWriteCreateRequest request) throws ParseException {
        DimensionWriteUpdateRequest updateRequest = new DimensionWriteUpdateRequest();
        updateRequest.setId(request.getId());
        updateRequest.setCode(request.getDimensionCode());
        updateRequest.setUpdater(request.getUpdater());
        if (!StringUtils.isEmpty(request.getDimensionStatus())) {
            updateRequest.setStatus(Integer.parseInt(request.getDimensionStatus()));
        }
        updateRequest.setValue(request.getDimensionValue());
        updateRequest.setRuleName(request.getRule());
        updateRequest.setRuleValue(request.getRuleValue());
        updateRequest.setDetails(request.getDetails());
        updateRequest.setStrategyId(request.getStrategyId());
        updateRequest.setExecuteAction(Objects.nonNull((request.getExecuteAction())) && request.getExecuteAction());
        if (!CollectionUtils.isEmpty(request.getValid())) {
            SimpleDateFormat sdf = new SimpleDateFormat(DateUtils.DATE_FORMAT);
            updateRequest.setValidBeginTime(sdf.parse(request.getValid().get(0)));
            Date lastTime = DateUtils.getLastTime(request.getValid().get(1));
            updateRequest.setValidEndTime(lastTime);
        }


        return updateRequest;
    }

    public static StrategySDO convertToSdoFbRequest(FbGenerateOrderSwitchRequest request) {
        StrategySDO strategySDO = new StrategySDO();
        strategySDO.setId(request.getId());
        strategySDO.setName(request.getStrategyName());
        strategySDO.setGmtCreate(new Date());
        strategySDO.setStatus("1");
        //        strategySDO.setCreator(request.getCreator());
        //        strategySDO.setPriority(request.getPriority());
        //        strategySDO.setDimensionType(request.getDimensionType());
        //        strategySDO.setShare(request.getShare());
        if (!CollectionUtils.isEmpty(request.getValidateTime())) {
            SimpleDateFormat sdf = new SimpleDateFormat("yyyy-MM-dd HH:mm:ss");
            try {
                Date begin = sdf.parse(request.getValidateTime().get(0));
                Date lastTime = DateUtils.getLastTime(request.getValidateTime().get(1));
                strategySDO.setValidBeginTime(begin);
                // 结束时间默认23:59:59
                strategySDO.setValidEndTime(lastTime);
            } catch (ParseException e) {
                e.printStackTrace();
            }
        }
        strategySDO.setType(request.getType());
        strategySDO.setOrganizationCode(request.getOrgCode());
        //        strategySDO.setOrganizationName(request.getOrgCode());
        //        strategySDO.setStatus(request.getStatus());
        List<DimensionSDO> dimensionSDOS = new ArrayList<>();
        //维度
        DimensionSDO dimensionSDO = new DimensionSDO();
        dimensionSDO.setId(request.getSwitchId() == null ? null :Long.valueOf(request.getSwitchId()));
        dimensionSDO.setCode(DimensionTypeEnum.ORGANIZE.getCode());
        dimensionSDO.setValue(request.getOrgCode());
        dimensionSDO.setRuleName(RuleTypeEnum.NUM_VALUE.getCode());

        //modify by 皓晖 at 20211219 for 新增自动生成订单策略,开关关闭报空指针 begin
        Boolean isGenerate = request.getIsGenerate();
        if(isGenerate != null && isGenerate){
            dimensionSDO.setRuleValue("1");
        }else{
            dimensionSDO.setRuleValue("0");
        }
        //modify by 皓晖 at 20211219 for 新增自动生成订单策略,开关关闭报空指针 end

        dimensionSDO.setStatus("1");
        dimensionSDOS.add(dimensionSDO);
        strategySDO.setDimensionSDOList(dimensionSDOS);
        return strategySDO;
    }

    public static void main(String[] args) {
        Boolean test = null;
        System.out.println(test);
        System.out.println(test?"1":"0");
    }
}
